package com.example.shiro.shiro;

import com.alibaba.fastjson.JSONArray;
import com.example.shiro.model.Permissions;
import com.example.shiro.model.Role;
import com.example.shiro.model.User;
import com.example.shiro.service.LoginService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;

/**
 * @description:
 * @author: guoc
 * @createDate: 2020/4/24 17:09
 */
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private LoginService loginService;


    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取用户名
        String name = (String)principalCollection.getPrimaryPrincipal();
        //根据用户名去数据库查询用户信息
        User user = loginService.getUserByName(name);
        //添加角色和权限
        //用户角色权限信息对象
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        String roles = user.getRoles();
        List<Role> rolelist = JSONArray.parseArray(roles, Role.class);
        for (Role role:rolelist){
            simpleAuthorizationInfo.addRole(role.getRoleName());
            for (Permissions permissions :role.getPermissions()){
                simpleAuthorizationInfo.addStringPermission(permissions.getPermissionsName());
            }
        }
        return simpleAuthorizationInfo;
    }
    //身份验证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //加这一步的目的是在Post请求的时候会先进认证，然后在到请求
        if (authenticationToken.getPrincipal() == null) {
            return null;
        }
        //获取用户名
        String name = authenticationToken.getPrincipal().toString();
        User user = loginService.getUserByName(name);
        if (user==null){
            //报错
            return null;
        }else {
            //这里验证authenticationToken和simpleAuthenticationInfo的信息
            //用户认证信息
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(name, user.getPassWord(), getName());
            return simpleAuthenticationInfo;
        }
    }
}
